import { VirtualChild } from "./virtualTreeChildren";
import { baseChildrenBuilder, EOChild } from "./childrenBuilder";
import { mve, BuildResult, onceLife, InitResult, orRun, Watcher, LifeModelReturn, newLifeModel } from "./util";
/**
 * 子元素集片段是动态生成的，watchAfter后直接新入
 * @param fun 
 */
export function ifChildren<EO>(
	fun: (me: mve.LifeModel) => EOChild<EO> | null
): EOChild<EO> {
	return function (parent, me) {
		let currentInit: BuildResult | void
		let currentDestroy: InitResult


		let virtualChild: VirtualChild<EO> | void
		let currentLifeModel: LifeModelReturn

		const life = onceLife(function () {
			currentDestroy = orRun(currentInit)
			return function () {
				w.disable()
				currentLifeModel.destroy()
				orRun(currentDestroy)
			}
		})
		const w = Watcher.ofExp(
			function () {
				if (currentLifeModel) {
					currentLifeModel.destroy()
				}
				currentLifeModel = newLifeModel()
			},
			function () {
				return fun(currentLifeModel.me)
			},
			function (children) {
				if (currentDestroy) {
					if (life.isInit) {
						currentDestroy()
					}
					currentDestroy = null
				}
				currentInit = null

				if (virtualChild) {
					parent.remove(0)
					virtualChild = null
				}
				if (children) {
					//初始化
					virtualChild = parent.newChildAtLast()
					currentInit = baseChildrenBuilder(currentLifeModel.me, children, virtualChild)
					if (life.isInit) {
						currentDestroy = orRun(currentInit)
					}
				}
			}
		)
		return life.init
	}
}